<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/3
 * Time: 16:14
 */

namespace app\shop;


use app\common\Common;
use app\data\OrderData;
use app\data\ProxyDate;
use app\data\ShopData;
use baidu\BaiDuSDK;
use Endroid\QrCode\QrCode;
use think\Db;

class Shop extends Base
{
    /**
     * 商户名称长度限制
     * @var array
     */
    private $shopName = [1, 50];

    /**
     * 商户简介长度限制
     * @var array
     */
    private $shopIntroduce = [1, 3000];

    /**
     * 商户副标题长度限制
     * @var array
     */
    private $subtitle = [0, 100];

    /**
     * 分类排序字段
     * @var array
     */
    private $typeSort = ['sort_lv'];

    /**
     * 分类排名商户字段
     * @var array
     */
    private $typeShopSort = ['type_lv'];

    /**
     * 排序方法
     * @var array
     */
    private $sortType = ['asc', 'desc'];

    /**
     * 首页排序字段
     * @var array
     */
    private $homeSort = ['hot_lv'];

    /**
     * 分类名称长度限制
     * @var array
     */
    private $typeName = [1, 20];

    /**
     * 商户分类排序字段
     * @var array
     */
    private $shopTypeSort = ['create_time'];

    private $commentSort = ['create_time', 'comment_integral'];

    /**
     * 商品排序
     * @var array
     */
    private $goodsSort = ['goods_hot', 'goods_new', 'create_time'];

    private $sort = ['create_time'];

    private $proxySort = ['create_time'];

    /**
     * 商户详细地址
     * @var int
     */
    private $areaInfo = [1, 200];
    //开户人姓名长度限制
    private $bank_user_name = [1, 20];
    //开户银行姓名长度
    private $bank_name = [1, 200];

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 基本校验
     * @param $type_id
     * @param $shop_introduce
     * @param $shop_name
     * @param $shop_type
     * @param $subtitle
     * @param $img
     * @param $shop_no
     * @param $shop_user_name
     * @param $shop_we_chat
     * @return array
     */
    private function check($type_id, $shop_introduce, $shop_name, $shop_type, $subtitle, $img, $shop_no,
                           $shop_user_name, $shop_we_chat)
    {
        $check = [
            ['drh_shop_type', 'id', $type_id, '不存在此分类'],
        ];
        //校验字段是否存在
        foreach ($check as $k => $v) {
            if (Common::checkTableFields($v[0], $v[1], $v[2]) == $this->f_code) {
                return ['code' => $this->f_code, 'msg' => $v[3]];
            }
        }
        //校验字符串长度
        $check = [
            '商户名称' => ["{$this->shopName[0]},{$this->shopName[1]}}", $shop_name],
            '商户简介' => ["{$this->shopIntroduce[0]},{$this->shopIntroduce[1]}}", $shop_introduce],
            '商户副标题' => ["{$this->subtitle[0]},{$this->subtitle[1]}}", $subtitle],
            '商户用户名称' => ["{$this->shopName[0]},{$this->shopName[1]}}", $shop_user_name],
            '商户微信号' => ["{$this->shopName[0]},{$this->shopName[1]}}", $shop_we_chat],
        ];
        $res = Common::checkLength($check);
        if ($res['code'] == $this->f_code) {
            return $res;
        }


        if ($shop_type != 0 && $shop_type != 1) {
            return ['code' => $this->f_code, 'msg' => '请选择商户类型'];
        }
        if (empty($img['id']) || empty($img['license'])) {
            return ['code' => $this->f_code, 'msg' => '请上传审核照片'];
        }
        if (!Common::checkTel($shop_no)) {
            return ['code' => $this->f_code, 'msg' => '手机号不合法'];
        }
        return ['code' => $this->t_code];
    }

    /**
     * 添加商户
     * @param $user_id
     * @param $shop_name
     * @param $shop_logo
     * @param $shop_introduce
     * @param $type_id
     * @param $shop_type
     * @param $img
     * @param $subtitle
     * @param $tel
     * @param $city_id | 市
     * @param $province_id | 省
     * @param $district_id | 区、县
     * @param $address | 详细地址
     * @param $shop_user_name | 详细地址
     * @param $shop_we_chat | 详细地址
     * @return \think\response\Json
     */
    public function addShop($user_id, $shop_name, $shop_logo, $shop_introduce, $type_id, $tel, $shop_user_name = "V1暂不修改", $shop_we_chat = "V1暂不修改",
                            $shop_type, $img, $subtitle, $city_id, $province_id, $district_id, $address)
    {
        $res = $this->check($type_id, $shop_introduce, $shop_name, $shop_type, $subtitle, $img, $tel
            , $shop_user_name, $shop_we_chat);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        //校验商户名称是否重复
        if (Common::checkTableFields('drh_shop', 'shop_name', $shop_name) == $this->t_code) {
            return json(['code' => $this->f_code, 'msg' => '商户名称已存在']);
        }

        //校验商户名称是否重复
        $checkTab = Db::query("SELECT shop_type FROM drh_shop WHERE user_id=".$user_id);
        if(count($checkTab) > 1){
                        return json(['code' => $this->f_code, 'msg' => '创建失败']);
        }else{

            $checkTab = Common::er_array($checkTab)[0]??3;

            if($checkTab == 2 && $shop_type == 2){
                return json(['code' => $this->f_code, 'msg' => '创建失败']);
            }elseif ($checkTab == 1 && $shop_type == 1){
                return json(['code' => $this->f_code, 'msg' => '创建失败']);
            }elseif ($checkTab == 0 && $shop_type == 0){
                return json(['code' => $this->f_code, 'msg' => '创建失败']);
            }
        }
        // if (Common::checkTableFields('drh_shop', 'user_id', $user_id) == $this->t_code) {
        //     return json(['code' => $this->f_code, 'msg' => '每个人只能拥有一个账户']);
        // }

//        $tel = Common::getTableValue('drh_user_info', 'user_tel', 'id', $user_id);
//        if (empty($tel)) {
//            return json(['code' => $this->f_code, 'msg' => '请填写合法创始人']);
//        }

        $shop = new ShopData();
        Db::startTrans();
        try {
            $res = $shop->addShop($user_id, $shop_name, $shop_logo, $shop_introduce, $type_id,
                $shop_type, json_encode($img), $subtitle, $tel, $shop_user_name, $shop_we_chat);
            $result = $this->addShopCity($res['data'], $city_id, $province_id, $district_id, $address);
            if ($result['code'] == $this->f_code) {
                Db::rollback();
                return json($result);
            }
            Db::commit();
            return json($res);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => $this->f_code, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 修改
     * @param $user_id
     * @param $shop_id
     * @param $shop_name
     * @param $shop_logo
     * @param $shop_introduce
     * @param $type_id
     * @param $shop_type
     * @param $img
     * @param $subtitle
     * @param $city_id
     * @param $province_id
     * @param $district_id
     * @param $address
     * @param $tel
     * @param $shop_user_name
     * @param $shop_we_chat
     * @return \think\response\Json
     */
    public function editShop($user_id, $shop_id, $shop_name, $shop_logo, $shop_introduce, $tel, $shop_user_name = "V1暂不修改", $shop_we_chat = "V1暂不修改",
                             $type_id, $shop_type, $img, $subtitle, $city_id, $province_id, $district_id, $address)
    {
        $res = $this->check($type_id, $shop_introduce, $shop_name, $shop_type, $subtitle, $img, $tel
            , $shop_user_name, $shop_we_chat);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }

        $id = Common::getTableValue('drh_shop', 'id', 'shop_name', $shop_name);
        if ($id != $shop_id && !empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '商户名称已存在']);
        }
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在此商户']);
        }
        $shop = new ShopData();
        Db::startTrans();
        try {
            $res = $shop->editShop($user_id, $shop_id, $shop_name, $shop_logo,
                $shop_introduce, $type_id, $shop_type, json_encode($img), $subtitle, $tel, $shop_user_name, $shop_we_chat);
            $result = $this->editShopCity($shop_id, $city_id, $province_id, $district_id, $address);
            if ($result['code'] == $this->f_code) {
                Db::rollback();
                return json($result);
            }
            Db::commit();
            return json($res);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => $this->f_code, 'msg' => $e->getMessage()]);
        }

    }

    /**
     * 删除商户
     * @param $user_id
     * @param $shop_id
     * @return \think\response\Json
     */
    public function delShop($user_id, $shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在此商户']);
        }
        $shop = new ShopData();

        return json($shop->delShop($user_id, $shop_id));
    }

    /**
     * 商户详细信息
     * @param $shop_id
     * @return \think\response\Json
     */
    public function shopInfo($shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在此商户']);
        }
        $shop = new ShopData();
        $res = $shop->shopInfo($shop_id);
        $res['comment_integral'] = $shop->getAllComment($shop_id);
        $res['img'] = json_decode($res['img']);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res
        ]);
    }


    /**
     * 首页人气商户展示
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showShop($recover_status=0,$page = 1, $pre = 15, array $sort = ['hot_lv' => 'asc'])
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->homeSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $b = ($page-1)*$pre;
        $shop = new ShopData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $shop->showList($b, $pre, $sort,$recover_status),
            'total' => $shop->total(' recover_status = 0 and verify_status = 1 and shop_type < 2'),
        ]);
    }

    public function changeShopHot($base_id, $shop_id, $hot_lv)
    {
        if ($base_id != 1 || $shop_id == 1) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        if ($hot_lv <= 0 || $hot_lv >= 65535) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $shop = new ShopData();
        return json($shop->changeShopHot($shop_id, $hot_lv));
    }

    /**
     * 类别展示
     * @param array $sort
     * @return \think\response\Json
     */
    public function showType(array $sort = ['sort_lv' => 'asc'])
    {
        $res = Common::checkSortCondition($this->typeSort, $sort, $this->sortType);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }

        $shop = new ShopData();

        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $shop->showType($sort),
        ]);
    }

    /**
     * 类别下商户展示
     * @param $type_id
     * @param array $sort
     * @param int $pre
     * @param int $page
     * @return \think\response\Json
     */
    public function showTypeShop($type_id, array $sort = ['type_lv' => 'asc'], $pre = 15, $page = 1)
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->typeShopSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }

        if (Common::checkTableFields('drh_shop_type', 'id', $type_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在此分类']);
        }
        $shop = new ShopData();

        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $shop->showTypeShop($type_id, $page, $pre, $sort),
            'total' => $shop->total(' recover_status = 0 and verify_status=1 and  type_id= ' . $type_id),
        ]);
    }

    public function checkType($shop_id, $type_name)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return ['code' => $this->f_code, 'msg' => '不存在该商户'];
        }
        $check = ['商品分类' => ["{$this->typeName[0]},{$this->typeName[1]}}", $type_name],];
        $res = Common::checkLength($check);
        if ($res['code'] == $this->f_code) {
            return $res;
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return $res;
        }
        return ['code' => $this->t_code];
    }

    private function checkShopVerify($shop_id)
    {
        $res = Common::getTableValue('drh_shop', 'verify_status', 'id', $shop_id);
        if ($res != 1) {
            return ['code' => $this->f_code, 'msg' => '商户正在审核,请稍后在试'];
        }
        return ['code' => $this->t_code];
    }

    /**
     * 添加商品分类
     * @param $shop_id
     * @param $type_name
     * @param $lv
    //     * @param $parent_type_id , $parent_type_id = 0
     * @return \think\response\Json
     */
    public function addGoodsType($shop_id, $type_name, $lv = 0)
    {
        $res = $this->checkType($shop_id, $type_name);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $id = Common::getTableValue('drh_goods_type', 'shop_id', 'type_name', $type_name);
        if ($id == $shop_id) {
            return json(['code' => $this->f_code, 'msg' => '存在此分类']);
        }

        $shop = new ShopData();
        $count = $shop->total(' shop_id= ' . $shop_id, 'drh_goods_type');
        if ($count >= 30) {
            return json(['code' => $this->f_code, 'msg' => '分类最多30个']);
        }
        return json($shop->addGoodsType($shop_id, $type_name, $lv));
    }

    /**
     * 修改商品分类
     * @param $shop_id
     * @param $type_name
     * @param int $lv
    //     * @param int $parent_type_id  //, $parent_type_id=0
     * @param int $type_id
     * @return \think\response\Json
     */
    public function editGoodsType($shop_id, $type_id, $type_name, $lv = 0)
    {
        $res = Common::getTableValue('drh_goods_type', 'shop_id', 'id', $type_id);
        if ($res == 0) {
            return json(['code' => $this->f_code, 'msg' => '系统分类不允许修改']);
        }
        $res = $this->checkType($shop_id, $type_name);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $id = Common::getTableValue('drh_goods_type', 'id', 'type_name', $type_name);
        if ($id != $type_id && !empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '类别名称以存在']);
        }
        $shop = new ShopData();
        return json($shop->editGoodsType($shop_id, $type_name, $lv, $type_id));
    }

    /**
     * 删除商品分类
     * @param $shop_id
     * @param $type_id
     * @return \think\response\Json
     */
    public function delGoodsType($shop_id, $type_id)
    {
        $res = Common::getTableValue('drh_goods_type', 'shop_id', 'id', $type_id);
        if ($res == 0) {
            return json(['code' => $this->f_code, 'msg' => '系统分类不允许删除']);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        }
        if (Common::checkTableFields('drh_goods_type', 'id', $type_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该分类']);
        }
        $shop = new ShopData();
        $count = $shop->total(' shop_id= ' . $shop_id . ' and goods_type_id=' . $type_id . ' and is_shelves=1', 'drh_goods');
        if ($count != 0) {
            return json(['code' => $this->f_code, 'msg' => '该分类下存在商品 无法删除该分类']);
        }
        return json($shop->delGoodsType($shop_id, $type_id));
    }

    /**
     * 显示商品分组
     * @param $shop_id
     * @return \think\response\Json
     */
    public function showGoodsType($shop_id)
    {
        $shop = new ShopData();
        return json($shop->showGoodsType($shop_id));
    }

    /**
     * 添加轮播商品
     * @param $shop_id
     * @param $goods_id
     * @param $img
     * @return \think\response\Json
     */
    public function addTypeRotation($shop_id, $goods_id, $img)
    {
        $shop = new ShopData();
        $count = $shop->total(' shop_id= ' . $shop_id, 'drh_shop_carousel_img');
        if ($count >= 5) {
            return json(['code' => $this->f_code, 'msg' => '商品轮播图最多5张']);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        }
//        $img = json_decode(Common::getTableValue('drh_goods', 'goods_img', ['id', 'shop_id'], [$goods_id, $shop_id]));
//        if (empty($img)) {
//            return json(['code' => $this->f_code, 'msg' => '该商品没有图片']);
//        }
//        $img = $img[0];
//        if (!$shop->checkGoods($shop_id, $goods_id)) {
//            return json(['code' => $this->f_code, 'msg' => '不存在该商品']);
//        }
        return json($shop->addTypeRotation($shop_id, $goods_id, $img));
    }

    /**
     * 删除轮播图
     * @param $shop_id
     * @param $id
     * @return \think\response\Json
     */
    public function delTypeRotation($shop_id = 1, $id = 2)
    {
        $ids = Common::getTableValue('drh_shop_carousel_img', 'shop_id', ['id', 'shop_id'], [$id, $shop_id]);
        if (empty($ids)) {
            return json(['code' => $this->f_code, 'msg' => '轮播图删除错误']);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        return json($shop->delTypeRotation($shop_id, $id));
    }

    /**
     * 显示轮播图
     * @param $shop_id
     * @return \think\response\Json
     */
    public function showTypeRotation($shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        return json($shop->showTypeRotation($shop_id));
    }

    /**
     * 展示商户的分类
     * @param $shop_id
     * @param array $sort
     * @param $status
     * @return \think\response\Json
     */
    public function showTypeGoods($shop_id, array $sort = ['create_time' => 'asc'], $status = 1)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $res = Common::checkSortCondition($this->shopTypeSort, $sort, $this->sortType);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        $res = $shop->showGoodsType($shop_id);
        if (empty($res['data'])) {
            $data = [];
        } else {
            $data = $status == 1 ? $this->showGoodsList($shop_id, $res['data'][0]['id'], $status) : '';
        }
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $res['data'],
                'data' => $data,
            ]
        ]);
    }

    /**
     * 展示商户分类下的商品
     * @param $shop_id
     * @param $type_id
     * @param int $page
     * @param int $pre
     * @param int $is_shelves
     * @param array $sort
     * @param $status
     * @return \think\response\Json
     */
    public function showGoodsList($shop_id, $type_id, $status = 0, $page = 1, $pre = 15, $is_shelves = 1, array $sort = ['create_time' => 'desc'])
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->goodsSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        $data = $shop->showGoodsList($shop_id, $page, $pre, $sort, $is_shelves, $type_id);
        $data = Common::arrayValueChange($data, 'goods_attr_value');
        $data = Common::arrayValueChange($data, 'goods_info');
        $data = $this->getImage($data);
        if ($status == 1) {
            return $data;
        } else {
            return json([
                'code' => $this->t_code,
                'msg' => 'OK',
                'data' => $data
            ]);
        }
    }
    //展示商户分类下的代理商品
    public function showGoodsList_agency($shop_id, $type_id, $status = 0, $page = 1, $pre = 15, $is_shelves = 1, array $sort = ['a.create_time' => 'desc'])
    {
//        echo 1;
//        exit;
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->goodsSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        $data = $shop->showGoodsList_agency($shop_id, $page, $pre, $sort, $is_shelves, $type_id);
        foreach ($data as $k=>$v){
            try{
                $data[$k]['goods_img'] = json_decode($v['goods_img'],true)??unserialize($v['goods_img']);
                $data[$k]['goods_attr_value'] = json_decode($v['goods_attr_value'],true)??unserialize($v['goods_attr_value']);
            }catch (\Exception $e){
                return json([
                    'code' => $this->f_code,
                    'msg' =>  $e->getMessage()."序列化数据录入错误"
                ]);
            }
        }
        if ($status == 1) {
            return $data;
        }else{
            return json([
                'code' => $this->t_code,
                'msg' => 'OK',
                'data' => $data
            ]);
        }
    }
    /**
     * 显示商品详情
     * @param $goods_id
     * @param $is_shelves
     * @param $status
     * @return \think\response\Json
     */
    public function showGoods($goods_id, $is_shelves = 1, $status = 0)
    {
        if (Common::checkTableFields('drh_goods', 'id', $goods_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商品']);
        }

        $shop = new ShopData();
        $data = $shop->showGoods($goods_id, $is_shelves);
        $carousel = json_decode($data['goods_img'])??unserialize($data['goods_img']);//商品图片
        unset($data['goods_img']);
        $goods_details = json_decode($data['goods_info'])??unserialize($data['goods_info']);//商品详情
        unset($data['goods_info']);
        $goods_attr = json_decode($data['goods_attr_value'])??unserialize($data['goods_attr_value']);//商品
        unset($data['goods_attr_value']);
        $json = $status == 0 ? 'json' : 'json_encode';
        return $json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'data' => empty($data) ? [] : $data,
                'carousel' => empty($carousel) ? [] : $carousel,
                'goods_details' => empty($goods_details) ? [] : $goods_details,
                'goods_attr' => empty($goods_attr) ? [] : $goods_attr,
            ]
        ], false);
    }


    private function getImage($data)
    {
        foreach ($data as $k => $v) {
            $goods_img = json_decode($v['goods_img']);
            $goods_img = empty($goods_img[0]) ? '' : $goods_img[0];
            $data[$k]['goods_img'] = $goods_img;
        }
        return $data;
    }

    /**
     * 显示7天交易量
     * @param $shop_id
     * @return \think\response\Json
     */
    public function showWekOrder($shop_id)
    {
        $shop = new ShopData();
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        }
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $data = $shop->showWekOrder($shop_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $data,
        ]);
    }


    /**
     * 热卖商品
     * @param $shop_id
     * @param $page
     * @param $pre
     * @return \think\response\Json
     */
    public function showGoodsNumber($shop_id, $page = 1, $pre = 15)
    {
        $shop = new ShopData();
        $res = $this->checkShopVerify($shop_id);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $res = Common::checkPageAndPre($page, $pre);
        if ($res['code'] != config('t_code')) {
            return json($res);
        }
        $data = $shop->showGoodsNumber($shop_id, $page = 1, $pre = 15);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $this->getImage($data),
        ]);
    }


    /**
     * 附近商家
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @param string $longitude | 经度
     * @param string $latitude | 维度
     * @return \think\response\Json
     */
    public function showAnnexShop($longitude = '116.4071700000', $latitude = '39.9046900000', $page = 1,
                                  $pre = 15, array $sort = ['create_time' => 'asc'])
    {
        $res = Common::checkShow($page, $pre, $this->sort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $sdk = new BaiDuSDK();
        $result = $sdk::getAddressComponent(config('ak'), $longitude, $latitude, $sdk::NO_Rim);

        $city_name = $result['result']['addressComponent']['city'];
        $city_code = $result['result']['addressComponent']['country_code'];
        if ($city_code == -1) {
            return json(['code' => $this->f_code, 'msg' => '经纬度错误']);
        }
        $shop = new ShopData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $shop->showAnnexShop($page, $pre, $sort, $city_name),
            'total' => $shop->getAnnexShopNumber($city_name)
        ]);
    }

    /**
     * 搜索商户信息
     * @param $name
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function searchShop($name, $page = 1, $pre = 15, array $sort = ['create_time' => 'asc'])
    {
        $res = Common::checkShow($page, $pre, $this->sort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $len = mb_strlen($name);
        if ($len > 10) {
            return json(['code' => $this->f_code, 'msg' => '搜索字符串过长']);
        }
        $shop = new ShopData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $shop->searchShop($name, $page, $pre, $sort),
            'total' => $shop->total("shop_name like '%{$name}%' and verify_status=1 and recover_status=0")
        ]);
    }

    private function checkBankCard($user_id, $user_name, $bank_name)
    {
        if (Common::checkTableFields('drh_shop', 'user_id', $user_id) == $this->f_code) {
            return ['code' => $this->f_code, 'msg' => '不存在该用户'];
        }

        $id = Common::getTableValue('drh_bank_card', 'user_id', ['id', 'type_id'], [$user_id, 0]);
        if (empty($id)) {
            return ['code' => $this->f_code, 'msg' => '每个个体只能添加一张银行卡'];
        }
        //校验字符串长度
        $check = [
            '开户人姓名' => ["{$this->bank_user_name[0]},{$this->bank_user_name[1]}}", $user_name],
            '开户银行名称' => ["{$this->bank_name[0]},{$this->bank_name[1]}}", $bank_name],
        ];
        $res = Common::checkLength($check);
        if ($res['code'] == $this->f_code) {
            return $res;
        }
        return ['code' => $this->t_code];
    }

    /**
     * 添加银行卡号    对公账户 和名称
     * @param $user_id
     * @param $user_name |  开户人姓名    对公账户
     * @param $bank_name |  开户人姓名    对公账户名称(什么什么名称)
     * @param $card |        开户卡号      对公账户(卡号)
     * @return array|\think\response\Json
     */
    public function addBankCard($user_id, $user_name, $bank_name, $card)
    {
        $res = $this->checkBankCard($user_id, $user_name, $bank_name);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if ($user_name == '对公账户') {

        } else {
            $res = Common::bankInfo($card);
            if ($res['code'] == $this->f_code) {
                return json($res);
            }
        }
        $shop = new ShopData();
        return json($shop->addBankCard($user_id, $user_name, $bank_name, time(), $res['msg'], $card));
    }

    /**
     * 修改银行卡号
     * @param $user_id
     * @param $user_name
     * @param $bank_name
     * @param $card
     * @return \think\response\Json
     */
    public function editBankCard($user_id, $user_name, $bank_name, $card)
    {
        $res = $this->checkBankCard($user_id, $user_name, $bank_name);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $res = Common::bankInfo($card);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        return json($shop->editBankCard($user_id, $user_name, $bank_name, $res['msg'], $card));
    }

    /**
     * 展示银行卡信息
     * @param $user_id
     * @return array|\think\response\Json
     */
    public function showBankCardInfo($user_id)
    {

        $id = Common::getTableValue('drh_bank_card', 'shop_id', ['id', 'type_id'], [$user_id, 0]);
        if (empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '请添加银行卡']);
        }
        $shop = new ShopData();
        $res = $shop->showBankCardInfo($user_id);
        $sub_cart = substr($res['card_number'], -4);
        $length = strlen($res['card_number']);
        $fill_array = array_fill(0, $length - 4, "*");
        $fill_str = implode($fill_array);
        $res['card_number'] = $fill_str . $sub_cart;
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $res
        ]);
    }



////////////////////////////////////////////----------后端------------\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

    /**
     * 大后台商户显示
     * @param $status
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showAdminShop($status, $page = 1, $pre = 15, array $sort = ['create_time' => 'desc'])
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->sort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        if ($status != 0 && $status != 1 && $status != 2) {
            return json(['code' => $this->f_code, 'msg' => '商户状态错误']);
        }
        $shop = new ShopData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $shop->showAdminShop($status, $page, $pre, $sort),
                'total' => $shop->total(" verify_status={$status} ")
            ],
        ]);
    }

    /**
     * 修改审核状态
     * @param $shop_id
     * @param $status
     * @return \think\response\Json
     */
    public function verifyShop($shop_id, $status)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        }

        if ($status != 1 && $status != 2) {
            return json(['code' => $this->f_code, 'msg' => '商户状态错误']);
        }
        $shop = new ShopData();
        return json($shop->verifyShop($shop_id, $status));
    }

    /**
     * 搜索商户信息
     * @param int $shop_no
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function searchAdminInfo($shop_no = 1, $page = 1, $pre = 15, array $sort = ['create_time' => 'desc'])
    {
        $id = Common::getTableValue('drh_shop', 'id', 'shop_no', $shop_no);
        if (empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '搜索的商户不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->proxySort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        $order = new OrderData();
        $total_money = $order->getTurnover($id);
        $commission = $order->getCommission($id);
        $info = $shop->showAdminShopInfo($id);
        $goods = $shop->showProxyGoods($id, $page, $pre, $sort);
        $info['total_money'] = $total_money;
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'info' => $info,
                'commission_money' => empty($commission) ? 0 : $commission,
                'goods' => $goods,
                'total' => $shop->total("proxy_goods_id > 0 and shop_id={$id}", 'drh_goods'),
            ]
        ]);
    }

    private function checkShopCity($shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return ['code' => $this->f_code, 'msg' => '不存在该商户'];
        }
        return ['code' => $this->t_code];
    }

    /**
     * 添加商户城市
     * @param $shop_id
     * @param $city_id
     * @param $province_id
     * @param $district_id
     * @param $address
     * @return array
     */
    public function addShopCity($shop_id, $city_id, $province_id, $district_id, $address)
    {

        $proxy_data = new ProxyDate();
        $p_res = $proxy_data->getArea($province_id);
        $c_res = $proxy_data->getArea($city_id);
        $d_res = $proxy_data->getArea($district_id);
        if ($c_res['parent_id'] != $province_id || $d_res['parent_id'] != $city_id) {
            return ['code' => $this->f_code, 'msg' => '非法操作'];
        }
        $check = [
            '商户详细地址' => ["{$this->areaInfo[0]},{$this->areaInfo[1]}}", $address]
        ];
        $res = Common::checkLength($check);
        if ($res['code'] == $this->f_code) {
            return $res;
        }
        $shop = new ShopData();
        return $shop->addShopCity($shop_id, $c_res['name'], $p_res['name'],
            $c_res['id'], $p_res['id'], $d_res['id'], $d_res['name'], $address);
    }

    /**
     * 修改商户城市
     * @param $shop_id
     * @param $city_id
     * @param $province_id
     * @param $district_id
     * @param $address
     * @return array
     */
    public function editShopCity($shop_id, $city_id, $province_id, $district_id, $address)
    {
        $res = $this->checkShopCity($shop_id);
        if ($res['code'] == $this->f_code) {
            return $res;
        }
        $proxy_data = new ProxyDate();
        $p_res = $proxy_data->getArea($province_id);
        $c_res = $proxy_data->getArea($city_id);
        $d_res = $proxy_data->getArea($district_id);
        if ($c_res['parent_id'] != $province_id || $d_res['parent_id'] != $city_id) {
            return ['code' => $this->f_code, 'msg' => '非法操作'];
        }
        $check = [
            '商户详细地址' => ["{$this->areaInfo[0]},{$this->areaInfo[1]}}", $address]
        ];
        $res = Common::checkLength($check);
        if ($res['code'] == $this->f_code) {
            return $res;
        }
        $shop = new ShopData();
        return $shop->editShopCity($shop_id, $c_res['name'], $p_res['name'], $c_res['id'],
            $p_res['id'], $d_res['id'], $d_res['name'], $address);
    }

    /**
     * 获取省份
     * @return \think\response\Json
     */
    public
    function showProvince()
    {
        $proxy_data = new ProxyDate();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $proxy_data->showProvince()
        ]);
    }

    /**
     * 获取市区
     * @param $p_id
     * @return \think\response\Json
     */
    public
    function showCity($p_id)
    {
        if (!Common::checkNumber($p_id)) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $proxy_data = new ProxyDate();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $proxy_data->showCity($p_id)
        ]);
    }

    /**
     * 获取区县
     * @param $c_id
     * @return \think\response\Json
     */
    public
    function showDistrict($c_id)
    {
        if (!Common::checkNumber($c_id)) {
            return json(['code' => $this->f_code, 'msg' => '非法操作']);
        }
        $proxy_data = new ProxyDate();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $proxy_data->showDistrict($c_id)
        ]);
    }

    public function test()
    {
//        $user_id = 1;
//        $app_id = config('app_id');
//        $secret = config('secret');
//        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$app_id}&secret={$secret}";
//        $res = Common::http_curl($url);
//        $accessToken = $res['access_token'];
//        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}";
//        $data = "{ \"path\": \"pages/welcome/welcome?user_id={$user_id}\", \"width\": 430}";
//        $root = dirname(dirname(__DIR__));
//
//        $res = Common::PostUrl($url, $data);
//        file_put_contents($root . DS . 'public' . DS . 'static' . "/regist_{$user_id}.png", $res);
//        return URL . DS . 'static' . DS . 'qrcode' . DS . "regist_{$user_id}.png";
        Common::checkShopOrGoodsPlugin(1,1);
    }

///////////////////////////////////-----------------新增功能--------------------------------/////////////////////////

    /**
     * 友情店铺
     * @param int $page
     * @param int $pre
     * @param $shop_id
     * @param array $sort
     * @return \think\response\Json
     */
    public function getFriendShipShop($page = 1, $pre = 15, $shop_id, $sort = ['create_time' => 'desc'])
    {
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->shopTypeSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $user_id = Common::getTableValue('drh_shop', 'user_id', 'id', $shop_id);
        if (empty($user_id)) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        $shop = new ShopData();
        $data = $shop->getFriendShipShop($page, $pre, $sort, $user_id);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $data
        ]);
    }

    /**
     * 友情店铺总数
     * @param $shop_id
     * @return \think\response\Json
     */
    public function getFriendShipShopTotal($shop_id)
    {
        $user_id = Common::getTableValue('drh_shop', 'user_id', 'id', $shop_id);
        if (empty($user_id)) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        $shop = new ShopData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $shop->getFriendShipShopTotal($user_id)
        ]);
    }

    /**
     * 商户 商户信息详情
     * @param $shop_id
     * @return \think\response\Json
     */
    public function getShopInfoInfo($shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '不存在该商户']);
        }
        $shop = new ShopData();
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => $shop->getShopInfoInfo($shop_id)
        ]);
    }

    /**
     * 展示品论列表
     * @param $shop_id
     * @param int $page
     * @param int $pre
     * @param int $goods_id
     * @param array $sort
     * @return \think\response\Json
     */
    public function showCommentOrder($shop_id, $page = 1, $pre = 15, $goods_id = 0, $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->commentSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $where = "a.shop_id={$shop_id} ";
        if ($goods_id !== 0) {
            if (Common::checkTableFields('drh_goods', 'id', $goods_id) == $this->f_code) {
                return json(['code' => $this->f_code, 'msg' => '商品不存在']);
            }
            $where .= " and b.goods_id={$goods_id}";
        }
        $shop = new ShopData();
        $data = $shop->showCommentOrder($where, $page, $pre, $sort);

        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => [
                'list' => $this->getCommentOrderImg($data),
                'total' => $shop->getCommentTotal($where)
            ]
        ]);
    }

    private function getCommentOrderImg($data)
    {
        foreach ($data as $k => $v) {
            $data[$k]['img'] = empty($v['img']) ? [] : json_decode($v['img']);
        }
        return $data;
    }

    public function showShopAttentionStatus($user_id, $shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        if (Common::checkTableFields('drh_user_info', 'id', $user_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '用户户不存在']);
        }
        $res = Common::getTableValue('drh_user_attention_shop', 'recover_status', ['user_id', 'shop_id'], [$user_id, $shop_id]);
        return json([
            'code' => $this->t_code,
            'msg' => 'OK',
            'data' => empty($res) ? 0 : $res
        ]);
    }

    /**
     * 添加友情店铺
     * @param $shop_id
     * @param $add_shop_id
     * @return \think\response\Json
     */
    public function addFriendShop($shop_id, $add_shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        if (Common::checkTableFields('drh_shop', 'id', $add_shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        $id = Common::getTableValue('drh_friend_shop', 'id', ['shop_id', 'add_shop_id'], [$shop_id, $add_shop_id]);
        if (!empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '请勿重复添加']);
        }
        $shop = new ShopData();
        $time = time();
        $shop->addFriendShop($shop_id, $add_shop_id, $time);
        return json(['code'=>$this->t_code,'msg'=>'添加成功']);
    }

    /**
     * 取消友情店铺
     * @param $shop_id
     * @param $add_shop_id
     * @return \think\response\Json
     */
    public function editFriendShop($shop_id, $add_shop_id)
    {
        $id = Common::getTableValue('drh_friend_shop', 'id', ['shop_id', 'add_shop_id'], [$shop_id, $add_shop_id]);
        if (empty($id)) {
            return json(['code' => $this->f_code, 'msg' => '访问数据错误']);
        }
        $shop = new ShopData();
        $shop->editFriendShop($shop_id, $add_shop_id);
        return json(['code'=>$this->t_code,'msg'=>'取消成功!']);
    }

    /**
     *
     * @param $shop_id
     * @param int $page
     * @param int $pre
     * @param array $sort
     * @return \think\response\Json
     */
    public function showFriendShop($shop_id,$page = 1, $pre = 5,
                                   array $sort = ['create_time' => 'desc'])
    {
        if (Common::checkTableFields('drh_friend_shop', 'shop_id', $shop_id) == $this->f_code) {
            return json(['code' => $this->t_code, 'msg' => '商户不存在','data'=>[]]);
        }
        //校验页码数和页码条数已经排序
        $res = Common::checkShow($page, $pre, $this->shopTypeSort, $this->sortType, $sort);
        if ($res['code'] == $this->f_code) {
            return json($res);
        }
        $shop = new ShopData();
        $data=$shop->showFriendShop($shop_id,$page,$pre ,$sort);
        return json([
            'code'=>$this->t_code,
            'msg'=>'OK',
            'data'=>[
                'list'=>$data,
                'total'=>Common::total("shop_id={$shop_id}",'drh_friend_shop')
            ]
        ]);
    }

    public function showShopPlugin($shop_id)
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        $shop = new ShopData();
        $res=$shop->showShopPlugin($shop_id);
        if (empty($res)){
            $res['shop_id']=$shop_id;
            $res['distribution_status']=1;
            $res['bargain_status']=1;
            $res['group_buy_status']=1;
            $res['game_status']=1;
        }

        return json([
            'code'=>$this->t_code,
            'msg'=>'OK',
            'data'=>$res
        ]);
    }

    public function editShopPlugin($shop_id,$distribution_status,$bargain_status,$group_buy_status,$game_status)
    {
        if(!in_array($distribution_status,[0,1]) ||
            !in_array($bargain_status,[0,1]) ||
            !in_array($group_buy_status,[0,1]) ||
            !in_array($game_status,[0,1])){
            return json(['code'=>$this->t_code,'msg'=>'参数数据错误']);
        }
        $shop = new ShopData();
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        if (Common::checkTableFields('drh_shop_plugin', 'shop_id', $shop_id) == $this->f_code) {
            $time=time();
            $shop->addShopPlugin($shop_id,$distribution_status,$bargain_status,$group_buy_status,$game_status,$time);

        }else{
            $shop->editShopPlugin($shop_id,$distribution_status,$bargain_status,$group_buy_status,$game_status);
        }
        return json(['code'=>$this->t_code,'msg'=>'修改成功']);
    }

    public function showShopUser($shop_id,$page=1,$pre=10,$sort=['create_time'=>'desc'])
    {
        if (Common::checkTableFields('drh_shop', 'id', $shop_id) == $this->f_code) {
            return json(['code' => $this->f_code, 'msg' => '商户不存在']);
        }
        $shop = new ShopData();
        $res=$shop->showShopUser($shop_id,$page,$pre,$sort);
        return json([
            'code'=>$this->t_code,
            'msg'=>'OK',
            'data'=>[
                'list'=>$res,
                'total'=>$shop->getShopUserTotal($shop_id)
            ]
        ]);

    }
    public function brokerage($id){
        return json([
            'code'=>$this->t_code,
            'msg'=>'OK',
            'data'=>[
                'list'=>Common::db_count("friendship_store","","drh_shop","id=".$id)[0]['friendship_store']??0,
            ]
        ]);
    }
    public function brokerage_set($id,$friendship_store){
        $brokerage_set =  Common::db_upload("drh_shop","friendship_store=".$friendship_store." where id=".$id);
        return json([
            'code'=>$brokerage_set?$this->t_code:$this->f_code,
            'msg'=>$brokerage_set?"ok":"失败",
        ]);
    }
}


